﻿using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.NoNet;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.出库管理
{
    /// <summary>
    /// 出库
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class TShippingOrderDetailController : ControllerBase
    {
        private readonly ILogRepository logRepository;
        private readonly SqliteContext sqliteContext;
        private readonly ITInventoryRepository tInventory;
        private readonly ITShippingLockCellRepository tShippingLockCell;
        private readonly ITWarehouseRepository tWarehouse;
        private readonly IRFIDRepository rFIDRepository;

        public ITShippingOrderDetailRepository _service { get; set; }

        public TShippingOrderDetailController(
            ITShippingOrderDetailRepository service,
            ITInventoryRepository tInventory,
            ITShippingLockCellRepository tShippingLockCell,
            ITWarehouseRepository tWarehouse,
            ILogRepository logRepository,
            IRFIDRepository rFIDRepository,
            SqliteContext sqliteContext
            )
        {
            _service = service;
            this.logRepository = logRepository;
            this.sqliteContext = sqliteContext;
            this.tInventory = tInventory;
            this.tShippingLockCell = tShippingLockCell;
            this.tWarehouse = tWarehouse;
            this.rFIDRepository = rFIDRepository; 
            this.logRepository = logRepository;
        }


        /// <summary>
        /// 往sqlite中添加数据
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost("AddSqliteDetail")]
        public IActionResult AddSqliteDetail(GroupShippingOrderDto item,int id)
        {
            if (item == null)
            {
                return Ok(BaseResult.Result("400", "请求参数为空"));
            }
            var list = _service.AddSqliteDetail(item,id,out var message);
            if (list)
            {
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }


        /// <summary>
        /// 带出所有器材
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetMaterialAll")]
        public IActionResult GetMaterialAll(string? mname, int? materialCategoryId, int pageIndex, int pageSize)
        {
            var list = _service.GetMaterialAll(out var totalCount,mname, materialCategoryId, pageIndex,pageSize);
            if (list == null)
            {
                return Ok(BaseResult.Result(null, "查询成功,暂无器材", "200",0));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200",totalCount));
        }

        /// <summary>
        /// 根据器材ID带出器材其他信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetMaterialById")]
        public IActionResult GetMaterialById(int id )
        {
            if( id < 0 )
            {
                return Ok(BaseResult.Result(false, "查询失败，Id错误", "500"));
            }
            var list  = _service.GetMaterialById(id);
            if (list == null )
            {
                return Ok(BaseResult.Result(null, "查询成功,暂无器材", "200"));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200"));
        }

        /// <summary>
        /// 根据OrderSn查询
        /// </summary>
        /// <param name="orderSn"></param>
        /// <returns></returns>
        [HttpGet("GetByOrderSnTShipping")]
        public IActionResult GetByOrderSnTShipping(string orderSn)
        {
            if (orderSn == null)
            {
                return Ok(BaseResult.Result(false, "查询失败，请求参数有误", "500"));
            }
            var list = _service.GetByOrderSnTShipping(orderSn);
            if (list == null)
            {
                return Ok(BaseResult.Result(null, "查询成功,，暂无数据", "200"));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200"));
        }

        /// <summary>
        /// 添加出库表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("AddTShippingOrderDetail")]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult AddTShippingOrderDetail(GroupShippingOrderDto model)
        {
            string uname = HttpContext.User.FindFirstValue("UserName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            model.NowUserId = uid;
            model.NowUserName = uname;
            var create = _service.AddTShippingOrderDetail(model,out string message);
            #region RFID功能
            ////遍历明细表 并添加到中间表中
            //var allCellCode = _service.GetAllCellCode(model);

            //#region 点亮标签
            //var task = rFIDRepository.GetRFIDMsgByCellCode(allCellCode);

            //RFIDMsgDto? data = rFIDRepository.RFIDLightUp("/api/" + $"{task.sign}" + "esl/direct", task);

            //if (data.error_code != 0)
            //{
            //    return Ok(BaseResult.Result(0, data.error_msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            //}
            //#endregion

            //#region 点亮巷道灯
            ////获取巷道
            //var troutwayModel = rFIDRepository.GetTroutway(out string msg, allCellCode);

            ////获取巷道点亮的参数
            //var lightModel = rFIDRepository.GetLightByRoadway(out msg, troutwayModel);

            ////点亮
            //RFIDMsgDto msgDto = rFIDRepository.RoadwayLightUp(msg, lightModel);

            //if (msgDto.error_code != 0)
            //{
            //    return Ok(BaseResult.Result(false, msg, "500"));
            //}
            //#endregion
            #endregion
            if (create)
            {
                string runame = HttpContext.User.FindFirstValue("RealName");
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "出库管理";
                logg.UserName = uname;
                logg.RealName = runame;                                 
                logg.UserId = uid;
                logg.Description = uname + "创建了出库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);

                //var AddSqlite = _service.AddSqliteDetail(model);
                //if (!AddSqlite)
                //{
                //    return Ok(BaseResult.Result("400", "存入sqlite失败"));
                //}
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /*
        /// <summary>
        /// 添加出库表 多个物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("AddTShippingOrderDetailPlus")]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult AddTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            var create = _service.AddTShippingOrderDetailPlus(model,out var msg);
            if (create)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "入库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了入库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, msg, "500"));
        }

        */
        /// <summary>
        /// 删除出库单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteTShippingOrderDetail")]
        public IActionResult DeleteTShippingOrderDetail(string OrderSn)
        {
            if (OrderSn == null)
            {
                return Ok(BaseResult.Result("400", "出库单号有误！"));
            }
            bool IsOK = _service.DeleteTShippingOrderDetail(OrderSn);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }


        /// <summary>
        /// 删除出库单  多个物料单版本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteTShippingOrderDetailPlus")]
        public IActionResult DeleteTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            if (model == null)
            {
                return Ok(BaseResult.Result("400", "请求参数有误！"));
            }
            bool IsOK = _service.DeleteTShippingOrderDetailPlus(model);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }


        /// <summary>
        /// 修改出库表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("UpdateTShippingOrderDetail")]
        public IActionResult UpdateTShippingOrderDetail(GroupShippingOrderDto model)
        {
            if(model.Id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            string uname = HttpContext.User.FindFirstValue("UserName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            model.NowUserId = uid;
            model.NowUserName = uname;
            var update = _service.UpdateTShippingOrderDetail(model);
            if (update)
            {             
                string runame = HttpContext.User.FindFirstValue("RealName");               
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "出库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了入库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }



        /// <summary>
        /// 修改出库表 多个物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("UpdateTShippingOrderDetailPlus")]
        public IActionResult UpdateTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            //if (model.Id <= 0)
            //{
            //    return Ok(BaseResult.Result("400", "Id有误！"));
            //}
            var update = _service.UpdateTshippingOrderDetailPlus(model);
            if (update)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "出库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了出库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }

        //[HttpGet("GetTest")]
        //public IActionResult GetTest()
        //{
        //    var list = _service.GetTest();
        //    if (list.Count >= 0)
        //    {
        //        return Ok(BaseResult.Result(list, "查询成功！", "200"));
        //    }
        //    return Ok(BaseResult.Result(null, "查询失败！", "500"));
        //}

        /// <summary>
        /// 显示出库表
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetAllTShippingOrderDetail")]
        public IActionResult GetAllTShippingOrderDetail(string? StartTime, string? EndTime, int? billType, int? status, int? warehouseid, int pageIndex, int pageSize)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            string rolecode = HttpContext.User.FindFirstValue("RoleCode");
            var list = _service.GetAllTShippingOrderDetail(StartTime, EndTime, billType,status,warehouseid,  rolecode, pageIndex, pageSize, out totalCount); 
            if (list.Count >= 0)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 显示出库表
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetAllTShippingOrderDetailPlus")]
        public IActionResult GetAllTShippingOrderDetailPlus(int? billType, int? houseid, string? name, int pageIndex = 1, int pageSize = 8)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            var list = _service.GetAllTShippingOrderDetailPlus(billType, houseid, name, pageIndex, pageSize, out totalCount);
            if (list.Count >= 0)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("GetTShippingOrderDetailById")]
        public IActionResult GetTShippingOrderDetailById(string OrderSn)
        {
            if(OrderSn == null || OrderSn == "")
            {
                return Ok(BaseResult.Result("400", "参数有误！"));
            }

            var orderDetail = _service.GetByIdTShippingOrderDetail(OrderSn);
            if (orderDetail != null)
            {
                return Ok(BaseResult.Result(orderDetail, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "未找到单号对应的数据！", "404"));
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut("UpdTShippingOrderDetailState")]
        public IActionResult UpdTShippingOrderDetailState(ReceivingOrderDetailDto m)
        {
            var list = _service.GetGroupShippingOrderDtoByOrdersn(m.OrderSN);
            if(list == null)
            {
                return Ok(BaseResult.Result(false, "修改失败", "500"));
            }
            var sqliteList = _service.AddSqliteDetail(list,list.Id,out var message);
            if (!sqliteList)
            {
                return Ok(BaseResult.Result(true, "修改sqlite数据库失败！", "500"));
            }
            bool IsOK = _service.UpdTShippingOrderDetailState(m);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }

        /// <summary>
        /// 入库后减去库存
        /// </summary>
        /// <returns></returns>
        [HttpPost("submitShipping")]
        public IActionResult submitShipping()
        {
            var list = _service.submitShipping(out var message);
            if (list)
            {
                return Ok(BaseResult.Result(list, "减去库存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 一键选定(弃用)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SelectTShippingOrderDetail(TShippingOrderDetail model)
        {
            var success = SelectTShippingOrderDetail(model);
            if (success != null)
            {
                return Ok(new { success = true, message = "选定成功", code = "200" });
            }
            else
            {
                return Ok(new { success = false, message = "选定失败,是否物料名称，库房，批次号，出库数量已选", code = "500" });
            }
        }

        /// <summary>
        /// 一键选定(弃用)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //[HttpPost("GetAllTShippingLockCell")]
        //public IActionResult GetAllTShippingLockCell(TShippingOrderDetail model)
        //{
        //    try
        //    {
        //        List<TShippingLockCell> selectedCells = new List<TShippingLockCell>();

        //        // 校验物料Id是否为空或无效
        //        if (model.MaterialId <= 0)
        //        {
        //            return BadRequest("请选择物料");
        //        }

        //        // 校验数量是否为空或无效
        //        if (model.Qty <= 0)
        //        {
        //            return BadRequest("请选择出库数量");
        //        }

        //        // 校验仓库Id是否为空或无效
        //        if (model.WarehouseId <= 0)
        //        {
        //            return BadRequest("请选择仓库");
        //        }

        //        selectedCells = _service.GetAllTShippingLockCell(model)
        //            .Where(cell =>
        //                cell.InventoryQty >= model.Qty && cell.WhId == model.WarehouseId &&
        //                cell.MaterialId == model.MaterialId)
        //            .ToList();

        //        return Ok(selectedCells);
        //    }
        //    catch (Exception ex)
        //    {
        //        return StatusCode(500, $"发生错误: {ex.Message}");
        //    }
        //}

        /// <summary>
        /// 根据物料Id返回批次和数量(之前)
        /// 现：根据选择的物料返回可选择的批次号下拉框
        /// 
        /// </summary>
        /// <param name="mid"></param>
        /// <param name="warehouseCode">库房编码</param>
        /// <param name="areaCode">库区编码</param>
        /// <param name="materialId">物料id</param>
        /// <param name="batchNO">批次号</param>
        /// <param name="qualityState">质量状态</param>
        /// <param name="expectedQTY">预计出库数量</param>
        /// <param name="ownerId">货主id</param>
        /// <param name="lockCellList">out 分配到的仓位</param>
        /// <param name="errorMsg">错误信息</param>
        /// <param name="orderDetailId">出库单详细Id</param>
        /// <param name="supplierId">供应商id</param>
        /// <param name="produceFactory">生产厂家</param>
        /// <returns></returns>
        [HttpGet("GetMaterialIdById")]
        public IActionResult GetMaterialIdById(int materialId, string? batchNO, int? qualityState, string? whCode, string? areaCode, string? produceFactory, int? ownerId, int? supplierId = null)
        {
            if (materialId <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var mobj = _service.GetMaterialIdById(materialId, batchNO,qualityState, whCode,areaCode,ownerId,supplierId,produceFactory);
            if (mobj != null)
            {
                return Ok(BaseResult.Result(mobj, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 一键选定 弃用
        /// </summary>
        /// <param name="materid"></param>
        /// <param name="count"></param>
        /// <param name="whid"></param>
        /// <param name="areaid"></param>
        /// <param name="supid"></param>
        /// <param name="owid"></param>
        /// <returns></returns>
        //[HttpGet("GetAllTShippingLockCell")]
        //public IActionResult GetAllTShippingLockCell(int materid = 0, int count = 0, int whid = 0, int areaid = 0, int supid = 0, int owid = 0)
        //{
        //    if (materid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "物料有误！"));
        //    }
        //    if (count <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "请选择出库数量！"));
        //    }
        //    if (whid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "库房有误！"));
        //    }
        //    if (areaid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "库区有误！"));
        //    }
        //    if (supid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "供应商有误！"));
        //    }
        //    if (owid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "货主有误！"));
        //    }
        //    var list = _service.GetAllTShippingLockCell(materid, count, whid, areaid, supid, owid);
        //    if (list != null)
        //    {
        //        return Ok(BaseResult.Result(list, "查询成功！", "200", 0));
        //    }

        //    return Ok(BaseResult.Result("200", "库存数量不足1，部分库存可能已被其它出库单锁定"));
        //}
        /// <summary>
        /// 一键选定 弃用
        /// </summary>
        /// <param name="materid"></param>
        /// <param name="count"></param>
        /// <param name="whid"></param>
        /// <param name="areaid"></param>
        /// <param name="supid"></param>
        /// <param name="owid"></param>
        /// <returns></returns>
        //[HttpGet("GetAllTShippingLockCell")]
        //public IActionResult GetAllTShippingLockCell(string? batchNO, int MaterialId, decimal Qty, string whCode, int? qualityState, string? areaCode, int? SupplierId, int? OwnerId, int? orderDetailId = null, string? produceFactory = "")
        //{


        //    //_service.GetAllTShippingLockCell(materid, count, whid, areaid, supid, owid);
        //    var res = tShippingLockCell.LockCell(whCode, areaCode, MaterialId, batchNO, qualityState, Qty, OwnerId, out var lockCellList, out var errorMsg, orderDetailId, SupplierId, produceFactory);
        //    if (res)
        //        return Ok(BaseResult.Result(lockCellList, "查询成功！", "200"));
        //    return Ok(BaseResult.Result(false, errorMsg, "500"));
        //}

        /// <summary>
        /// 获取货品明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetOneTShippingGoods")]
        public IActionResult GetOneTShippingGoods(int id, int pageIndex = 1, int pageSize = 8)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var goodsDetail = _service.GetOneTShippingGoodsDetail(id, pageIndex, pageSize, out totalCount);
            if (goodsDetail != null)
            {
                return Ok(BaseResult.Result(goodsDetail, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 根据名字获取
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetByNameShippingGoodsDetail")]
        public IActionResult GetByNameShippingGoodsDetail(string? name, int pageIndex = 1, int pageSize = 8)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var goodsDetail = _service.GetByNameShippingGoodsDetail(name, pageIndex, pageSize, out totalCount);
            if (goodsDetail != null && goodsDetail.Any())
            {
                return Ok(BaseResult.Result(goodsDetail, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 无网问题解决方案测试
        /// </summary>
        /// <returns></returns>
        //[HttpGet("GetTest")]
        //public IActionResult GetTest()
        //{
        //    for (int i = 0; i < 100000; i++)
        //    {
        //        //插入数据
        //        var data = new Dfgk { Code = "zh" + i, Name = "子涵" + i };
        //        sqliteContext.Dfgk.Add(data);
        //        sqliteContext.SaveChanges();
        //    }



        //    return Ok(sqliteContext.Dfgk);
        //}


        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadUserInfo")]
        public IActionResult UploadUserInfo(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;
                bool chongfu = false;
                bool dbchongfu = false;
                List<TShippingLockCell> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);
                    string? MaterialCategoryName = row.GetCell(0)?.StringCellValue;
                    string? MaterialCategoryCode = row.GetCell(1)?.StringCellValue;
                    string? Name = row.GetCell(2)?.StringCellValue;
                    string? Code = row.GetCell(3)?.StringCellValue;
                    string? ModelSpec = "";
                    if (row.GetCell(4)?.CellType == CellType.String)
                    {
                        ModelSpec = row.GetCell(4)?.StringCellValue;
                    }
                    else
                    {
                        ModelSpec = row.GetCell(4)?.NumericCellValue.ToString();
                    }
                    string? QualityStateName = row.GetCell(5)?.StringCellValue;
                    string? UnitName = row.GetCell(6)?.StringCellValue;
                    decimal? OutQty = (int?)row.GetCell(7)?.NumericCellValue;
                    decimal? Price = (decimal?)row.GetCell(8)?.NumericCellValue;
                    decimal? TotalPrice = (decimal?)row.GetCell(9)?.NumericCellValue;

                    //if (string.IsNullOrEmpty(Articlebarcode) || Articlebarcode == "0" || string.IsNullOrEmpty(Code) || Code == "0" || string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Shortname) || string.IsNullOrEmpty(UnitName) || string.IsNullOrEmpty(ModelSpec))
                    //{
                    //    continue;
                    //}
                    ////查询当前文件是否有重复的六九码
                    //chongfu = stuList.Where(x => x.Articlebarcode == Articlebarcode).Any();
                    //if (chongfu)
                    //{
                    //    message += Articlebarcode + "重复";
                    //    continue;
                    //}
                    ////查询库数据库中是否有重复的六九码
                    //dbchongfu = MaterialRepisotory.GetAll().Where(x => x.Articlebarcode == Articlebarcode).Any();
                    //if (dbchongfu)
                    //{
                    //    message += Articlebarcode + "重复";
                    //    continue;
                    //}

                    var user = new TShippingLockCell
                    {
                        MaterialCode = Code,
                        MaterialName = Name,
                        ModelSpec = ModelSpec,
                        MaterialCategoryName = MaterialCategoryName,
                        MaterialCategoryCode = MaterialCategoryCode,
                        QualityState = QualityStateName == "新品" ? 1 : 0,
                        Price = Price,
                        OutQty = OutQty,
                        TotalPrice = TotalPrice,
                        UnitName = UnitName,
                    };
                    stuList.Add(user);
                }
                if (stuList.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(null, "导入失败！" + message, "500"));
                }
                wb.Close();

                return Ok(BaseResult.Result(stuList, "导入成功！" + message, "200"));
            }
            catch (Exception)
            {
                throw;
            }
        }


        [HttpGet("GetTShippingOrder")]
        public IActionResult GetTShippingOrder(int pageIndex, int pageSize)
        {
            var list = _service.GetTShippingOrder(pageIndex, pageSize, out int totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200",totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 关联单号查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetShippingLockCells")]
        public IActionResult GetShippingLockCells(string OrderSn)
        {
            var list = _service.GetShippingLockCells(OrderSn,out string message);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(null, message, "500"));
        }

        /// <summary>
        /// 获取物料库存位置
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetPositionByMaterial")]
        public IActionResult GetPositionByMaterial(string materialCode)
        {
            var list = _service.GetPositionByMaterial(materialCode);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500"));
        }
    }
}